package com.mebs.model.logistics;

import org.jt.jet.util.JetUtils;

import javax.persistence.*;
import java.util.Set;
import java.text.NumberFormat;

import com.mebs.model.inventory.BoxSubItem;
import com.mebs.model.inventory.OrderItem;
import com.mebs.model.DimensionUnit;

/**
 * Created by Sergey Prasolov, sap@jensentechnologies.com Date: Mar 6, 2006, 7:51:28 PM
 */
@Entity()
@Table(name = "OVERPACKED_BOX")
@Inheritance(strategy = InheritanceType.JOINED)
@PrimaryKeyJoinColumn(name = "Id")
public class OverpackedBox extends Box {
    @OneToMany(fetch = FetchType.LAZY)
    @JoinColumn(name = "OverpackedBoxId")
    private Set<Box> boxes;

    /**
     * Constructors
     */

    public OverpackedBox()
    {
    }

    /**
     * Getters-setters
     */

    public Set<Box> getBoxes()
    {
        return boxes;
    }

    public void setBoxes(Set<Box> boxes)
    {
        this.boxes = boxes;
    }

    @Transient
    public boolean isDeletable()
    {
        return JetUtils.isEmpty(boxes);
    }

    @Transient
    public Integer getItemQuantity(BoxSubItem subItem)
    {
        if (JetUtils.isEmpty(boxes)) return 0;

        int qty = 0;

        for (Box box : boxes) {
            if (box instanceof StructuredBox)
                qty += ((StructuredBox) box).getItemQuantity(subItem);
            else if (box instanceof OverpackedBox)
                qty += ((OverpackedBox) box).getItemQuantity(subItem);
        }

        return qty;
    }

    @Transient
    public Integer getItemQuantity(OrderItem orderItem)
    {
        if (JetUtils.isEmpty(boxes)) return 0;

        int qty = 0;

        for (Box box : boxes) {
            if (box instanceof StructuredBox)
                qty += ((StructuredBox) box).getItemQuantity(orderItem);
            else if (box instanceof OverpackedBox)
                qty += ((OverpackedBox) box).getItemQuantity(orderItem);
        }

        return qty;
    }

    @Transient
    public static String getBoxesVolumeString(Box[] boxes) {
        double boxesVolume = 0;
        for (Box b : boxes) {
            boxesVolume += b.getCbmVolume();
        }
        if(Double.isInfinite(boxesVolume)) {
            boxesVolume = Double.MAX_VALUE;
        }

        NumberFormat nf = NumberFormat.getNumberInstance();
        nf.setMaximumFractionDigits(5);

        return nf.format(boxesVolume).replace(",", "");
    }

    /*
    @Transient
    public Double getVolume()
    {
        Double boxVolume = 0.0;
        Double bVolume = null;

        if (boxes != null) {
            for (Box b : boxes) {
                bVolume = b.getVolume();
                if (bVolume != null) {
                    boxVolume += bVolume;
                }
            }
        }

        if (boxVolume == 0.0) {
            boxVolume = null;
        }

        return boxVolume;
    }
    */
}
